package com.sesame.controller;

import com.sesame.framework.lock.service.DistributedLocker;
import com.sesame.framework.web.controller.AbstractWebController;
import com.sesame.framework.web.response.Response;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

@CommonsLog
@RestController
@RequestMapping("/test")
public class TestController extends AbstractWebController {

    @Autowired
    DistributedLocker locker;

    @RequestMapping("/readDb")
    public Response readDb() {
        String key = "redis_key_test";
        String name = Thread.currentThread().getName();

        log.info(MessageFormat.format("{0}尝试获取锁", name));
        try {
            locker.lock(key);
            log.info(MessageFormat.format("{0}获取锁成功", name));
            TimeUnit.SECONDS.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            locker.unlock(key);
            log.info(MessageFormat.format("{0} unlock success", name));
        }
        return returnSuccess();
    }
}
